#include "DungeonMap.hh"
#include <iostream>
#include <map>
#include <vector>
#include <algorithm>
#include <limits>

namespace DungeonRPG {

DungeonMap::DungeonMap() {}

void DungeonMap::setPlayerPosition(int x, int y) {
    // Update player's current position and mark as explored
    playerX = x;
    playerY = y;
    explored[{x, y}] = true;
}

void DungeonMap::setRoomMap(const std::map<std::pair<int, int>, Room*>& roomMap) {
    // Store reference to entire dungeon room layout
    this->roomMap = roomMap;
}

void DungeonMap::displayMap(int px, int py) const {
    std::cout << "\n=== DUNGEON MAP ===\n";

    if (roomMap.empty()) return;

    // Determine bounds of map for rendering
    int minX = std::numeric_limits<int>::max(), maxX = std::numeric_limits<int>::min();
    int minY = std::numeric_limits<int>::max(), maxY = std::numeric_limits<int>::min();

    for (const auto& [pos, _] : roomMap) {
        minX = std::min(minX, pos.first);
        maxX = std::max(maxX, pos.first);
        minY = std::min(minY, pos.second);
        maxY = std::max(maxY, pos.second);
    }

    // Render map row by row (top to bottom)
    for (int y = maxY; y >= minY; --y) {
        for (int x = minX; x <= maxX; ++x) {
            auto it = roomMap.find({x, y});
            if (it != roomMap.end()) {
                if (x == px && y == py) {
                    std::cout << "[P]"; // Player position
                } else if (explored.count({x, y}) && explored.at({x, y})) {
                    // Explored room, show by type
                    RoomType type = it->second->getType();
                    if (type == RoomType::Shop) {
                        std::cout << "[$]"; // Shop
                    } else if (type == RoomType::Treasure) {
                        std::cout << "[*]"; // Treasure
                    } else {
                        std::cout << "[X]"; // Normal room
                    }
                } else {
                    std::cout << "[?]"; // Unexplored room
                }
            } else {
                std::cout << "   "; // No room in this position
            }
        }
        std::cout << "\n";
    }
}

}
